package com.gy.controller.result;

import com.alibaba.excel.EasyExcel;
import com.gy.controller.common.UserHolder;
import com.gy.entity.Export.CustomCellWriteHandler;
import com.gy.entity.Export.ExportField;
import com.gy.entity.Export.ExportRequest;
import com.gy.entity.result.Other;
import com.gy.query.OtherQuery;
import com.gy.query.PapersQuery;
import com.gy.result.Result;
import com.gy.service.OtherService;
import com.gy.vo.PageVO;
import com.gy.vo.summary.OtherVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/other")
@Api(tags = "其他接口")
@CrossOrigin

public class OtherController {
    @Autowired
    private OtherService otherService;


    /**
     * 根据openid分页查看某个人的其他信息
     */
    @PostMapping("/get/other")
    @ApiOperation("根据openid查看某个人的其他信息")
    public Result<PageVO<Other>> getPapers(@RequestBody OtherQuery otherQuery){
        return otherService.getOther(otherQuery);
    }

    /**
     * 根据其他id主键删除其他
     */
    @DeleteMapping("/deleteById/{id}")
    @ApiOperation("根据其他id主键删除其他")
    public Result deleteById(@PathVariable Long id){
        return otherService.removeOtherById(id);
    }

    /**
     * 根据id主键查看其他
     */
    @GetMapping("/getOtherById/{id}")
    @ApiOperation("根据id主键查看其他")
    public Result getOtherById(@PathVariable Long id){
        return Result.success(otherService.getOtherById(id));
    }

    /**
     * 更改其他信息
     */
    @PutMapping("/update")
    @ApiOperation("更改其他信息")
    public Result update(@RequestBody Other other){
        return otherService.updateOther(other);
    }

    /**
     * 新增其他信息
     */
    @PostMapping("/save")
    @ApiOperation("新增其他信息")
    public Result AddOther(@RequestBody Other other){
        return otherService.saveOther(other);
    }


    /**
     * 根据多个id批量查询数据
     */
    @PostMapping("/getOtherByIds")
    @ApiOperation("根据多个id批量查询数据")
    public Result getOtherByIds(@RequestBody Long[] ids){
        return otherService.getOtherByIds(ids);
    }

    /**
     * excel批量导出
     */
    @PostMapping("/export")
    @ApiOperation("excel批量导出")
    public void exportPersonalAward(@RequestBody ExportRequest request, HttpServletResponse response) throws IOException {
        List<ExportField> fields = request.getFields();
        List<Map<String, Object>> data = request.getData();

        String fileName = "exported_Other.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 动态生成表头
        List<List<String>> head = fields.stream()
                .map(field -> Arrays.asList(field.getLabel()))
                .collect(Collectors.toList());

        // 将 Map<String, Object> 转换为 List<List<Object>>
        List<List<Object>> transformedData = data.stream()
                .map(map -> fields.stream()
                        .map(field -> map.get(field.getKey()))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 写入数据
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .registerWriteHandler(new CustomCellWriteHandler(fields))
                .sheet("其他信息")
                .doWrite(transformedData);
    }

    /**
     * 获取其他信息汇总
     */
    @GetMapping("/getSummary")
    @ApiOperation("获取其他信息汇总")
    public Result<List<OtherVO>> getSummary() {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户未登录或信息异常");
        }

        // 查询 "其他" 信息
        List<Other> otherList = otherService.lambdaQuery()
                .eq(Other::getUserId, userId)
                .select(Other::getTitle, Other::getAuthorRank, Other::getObtainTime)
                .list();

        // 映射到 OtherVO
        List<OtherVO> otherVOList = otherList.stream()
                .map(other -> OtherVO.builder()
                        .title(other.getTitle())
                        .authorRank(other.getAuthorRank())
                        .obtainTime(other.getObtainTime())
                        .build())
                .collect(Collectors.toList());

        return Result.success(otherVOList);
    }

}
